package com.yuanlang.common.util;

import java.util.Calendar;
        import java.util.regex.Pattern;

/**
 * 根据身份证获取性别、出生日期、年龄，支持15、18位身份证
 */
public class CertificateUtil {
    int idxSexStart = 16;
    int birthYearSpan = 4;
    String certificateNo,year,month,day;
    public CertificateUtil(String certificateNo) throws Exception {
        this.certificateNo = certificateNo;
        String myRegExpIDCardNo = "^\\d{6}(((19|20)\\d{2}(0[1-9]|1[0-2])(0[1-9]|[1-2][0-9]|3[0-1])\\d{3}([0-9]|x|X))|(\\d{2}(0[1-9]|1[0-2])(0[1-9]|[1-2][0-9]|3[0-1])\\d{3}))$";
        boolean valid=Pattern.matches(myRegExpIDCardNo,certificateNo)||(certificateNo.length() == 17 && Pattern.matches(myRegExpIDCardNo,certificateNo.substring(0,15)));
        if(!valid){
            throw new Exception("证件号码不规范!");
        }
        //如果是15位的证件号码
        if(certificateNo.length() == 15) {
            idxSexStart = 14;
            birthYearSpan = 2;
        }
        year = (birthYearSpan == 2 ? "19" : "") + certificateNo.substring(6, 6 + birthYearSpan);
        month = certificateNo.substring(6 + birthYearSpan, 6 + birthYearSpan + 2);
        day = certificateNo.substring(8 + birthYearSpan, 8 + birthYearSpan + 2);
    }
    public String getSex(){
        String idxSexStr = certificateNo.substring(idxSexStart, idxSexStart + 1);
        int idxSex = Integer.parseInt(idxSexStr) % 2;
        String sex = (idxSex == 1) ? "M" : "F";
        return sex;
    }
    public String getBirthday(){
        String birthday = year + '-' + month + '-' + day;
        return birthday;
    }
    public Integer getAge(){
        Calendar certificateCal = Calendar.getInstance();
        Calendar currentTimeCal = Calendar.getInstance();
        certificateCal.set(Integer.parseInt(year), Integer.parseInt(month)-1, Integer.parseInt(day));
        int yearAge = (currentTimeCal.get(currentTimeCal.YEAR)) - (certificateCal.get(certificateCal.YEAR));
        certificateCal.set(currentTimeCal.get(Calendar.YEAR), Integer.parseInt(month)-1, Integer.parseInt(day));
        int monthFloor = (currentTimeCal.before(certificateCal) ? 1 : 0);
        return  yearAge - monthFloor;
    }

    public static void main(String[] args) {
        System.out.println("1234".substring(0, 2));
    }
}